#!/usr/bin/ruby
require "rubygems"
require "opengl"
require "glut"
require "m3g"
require "pp"


class MyGLUTWidget
  def initialize
    GLUT.Init
    GLUT.InitWindowSize 256, 256
    GLUT.InitDisplayMode GLUT::GLUT_DOUBLE | GLUT::GLUT_RGB | GLUT::GLUT_DEPTH
    GLUT.CreateWindow "Ruby-M3G"

    initialize_scene

    GLUT.ReshapeFunc  method(:reshape).to_proc()
    GLUT.DisplayFunc  method(:display).to_proc()
    GLUT.KeyboardFunc method(:keyboard).to_proc()
    GLUT.MouseFunc    method(:mouse).to_proc()
    GLUT.IdleFunc     method(:idle).to_proc()

  end

  def initialize_scene

    positions = M3G::VertexArray.new 4, 3, 2
    position_values = [1,-1,0, 1,1,0, -1,-1,0, -1,1,0]
    positions.values[0,4] = position_values
    
    normals = M3G::VertexArray.new 4, 3, 1
    normal_values = [0,0,127, 0,127,0, 0,0,127, 0,127,0]
    normals.values[0,4] = normal_values

    scale = 1
    bias  = [0,0,0]
    vertices = M3G::VertexBuffer.new
    vertices.positions = positions, scale, bias
    vertices.normals = normals
    
    indices = [[0,1,2], [1,2,3]]
    strips  = [[3], [3]]
    trises  = [M3G::TriangleStripArray.new(indices[0], strips[0]),
               M3G::TriangleStripArray.new(indices[1], strips[1])]
    apps = [M3G::Appearance.new, 
            M3G::Appearance.new]
    
    mesh = M3G::Mesh.new vertices, trises, apps

    bg = M3G::Background.new
    bg.color = 0x7f66480e

    cam = M3G::Camera.new
    cam.translate 0,0,10

    @wld = M3G::World.new
    @wld.background = bg
    @wld.child << cam
    @wld.active_camera = cam
    @wld.child << mesh

    @width  = 0.0
    @height = 0.0
  end

  def reshape width, height
    @width  = width*1.0
    @height = height*1.0
    g3d = M3G::Graphics3D::instance
    g3d.viewport = 0,0,width,height
    @wld.active_camera.perspective = 45, width/(height*1.0), 0.1, 100
  end

  def display
    g3d = M3G::Graphics3D::instance
    g3d.render @wld
    GLUT.SwapBuffers()
  end
  
  def keyboard key, x, y
    if key == 113
      exit
    end
    GLUT.PostRedisplay
  end

  def mouse button, state, x, y
    puts "mouse, button=#{button}, state=#{state}, x=#{x}, y=#{y}"
    ri  = M3G::RayIntersection.new
    hit, ri = @wld.pick -1, x/@width, y/@height, @wld.active_camera
    puts "hit = #{hit}"
    if hit
      puts "node = #{ri.intersected}"
      puts "normal = #{ri.normal}"
      puts "submesh index = #{ri.submesh_index}"
    end
  end

  def idle
   GLUT.PostRedisplay
  end

  def start
    GLUT.MainLoop
  end

end


MyGLUTWidget.new.start

